package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsService {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 通过页面查询spu bo
     * 返回分页好的数据
     *
     * @param key      关键词-查询
     * @param saleable 可供出售--是否有库存
     * @param page     页面
     * @param rows     行
     * @return {@link PageResult}<{@link SpuBo}>
     */
    public PageResult<SpuBo> querySpuBoByPage(String key, Boolean saleable, Integer page, Integer rows) {
        Example example = new Example(Spu.class);//SPU商品集
        Example.Criteria criteria = example.createCriteria();
//        搜索词
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("title", "%" + key + "%");
        }
        //不为空设置库存
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
//      分页
        PageHelper.startPage(page, rows);

//          执行查询
        List<Spu> spus = this.spuMapper.selectByExample(example);//某个spu集合
        PageInfo<Spu> pageInfo = new PageInfo(spus);

        List<SpuBo> spuBos = new ArrayList<>();
//         封装为BO类--抽取为方法在保存商品的时候也需要
        spus.forEach(spu -> {
            SpuBo spuBo = new SpuBo();
            //复制
            BeanUtils.copyProperties(spu, spuBo);
            //查询分类名称
            //无法写入参数
            List<String> names = this.categoryService.queryNamesByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));

            // 拼接JSON
            spuBo.setCname(StringUtils.join(names, "-"));

            //无法写入参数
            //品牌名称
            spuBo.setBname(this.brandMapper.selectByPrimaryKey(spu.getBrandId()).getName());

            spuBos.add(spuBo);//
        });

        return new PageResult<>(pageInfo.getTotal(), spuBos);
    }


    /**
     * 发送消息辅助函数
     *
     * @param key   关键
     * @param spuId spu id
     */
    private void sendMsg(String key,Long spuId){
        try {
            this.amqpTemplate.convertAndSend("item."+key,spuId);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 新增--扩展类完成接收 json数据格式的spu信息有spuDetail & sku post请求
     * 因为表拆分-索引在主表，先增加主表
     */
    @Transactional
    public void saveGoods(SpuBo spuBo) {

        //新增SPU--spubo-直接继承的
        spuBo.setId(null);//自增--防止注入
        //对没有传递的数值进行设置
        spuBo.setValid(true);//有效--被删除
        spuBo.setSaleable(true);//上架

        spuBo.setCreateTime(new Date());//创建日期
        spuBo.setLastUpdateTime(spuBo.getCreateTime());//保持一致
        this.spuMapper.insertSelective(spuBo);

        //新增SPUDetail--sb--spu的一部分
        SpuDetail spuDetail = spuBo.getSpuDetail();
        spuDetail.setSpuId(spuBo.getId());
        this.spuDetailMapper.insertSelective(spuDetail);

        //新增SKU--注入其中的属性
        //新增STOCK--sku的一部分
        saveSkuAndStock(spuBo);

        //   RABBITMQ发送同步消息给goods和search
        sendMsg("insert",spuBo.getId());

    }


    private void saveSkuAndStock(SpuBo spuBo) {
        //属性中取出sku
        List<Sku> skus = spuBo.getSkus();
        //添加sku
        skus.forEach(sku -> {
            //sku--依赖于spu
            sku.setId(null);//自增--防止注入
            //对没有传递的数值进行设置
            sku.setSpuId(spuBo.getId());
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());

            this.skuMapper.insertSelective(sku);

            //stock--sku的一部分
            Stock stock = new Stock();

            stock.setSkuId(sku.getId());//一部分
            stock.setStock(sku.getStock());//库存

            this.stockMapper.insertSelective(stock);
        });

    }

    /**
     * 根据spuId查询spuDetail
     *
     * @param spuId
     * @return
     */
    public SpuDetail querySpuDetailBySpuId(Long spuId) {
        return this.spuDetailMapper.selectByPrimaryKey(spuId);
    }

    /**
     * 根据spuId查询sku的集合
     *
     * @param spuId
     * @return
     */
    public List<Sku> querySkusBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        //
        List<Sku> skus = this.skuMapper.select(sku);
        //库存在内的sku才是完整的sku
        skus.forEach(s -> {
            Stock stock = this.stockMapper.selectByPrimaryKey(s.getId());
            s.setStock(stock.getStock());
        });
        return skus;
    }

    /**
     * 更新产品
     * sku删除添加-具体参数，spu修改-商品集，
     *
     * @param spuBo spu博
     */
    @Transactional
    public void updateGoods(SpuBo spuBo) {
//        sku
        //之前是否存在
        List<Sku> skus = this.querySkusBySpuId(spuBo.getId());
        if (!CollectionUtils.isEmpty(skus)) {

            //获取sku的id转为集合long类型的集合
            List<Long> ids = skus.stream().map(s -> s.getId()).collect(Collectors.toList());
            //删除从表--id在stock 表中id存在的
            Example example = new Example(Stock.class);
            example.createCriteria().andIn("skuId", ids);
            //删除存在的stock
            this.stockMapper.deleteByExample(example);

            //删除存在的sku
            Sku sku = new Sku();
            sku.setSpuId(spuBo.getId());
            this.skuMapper.delete(sku);

        }
        //新增sku&stock
        saveSkuAndStock(spuBo);

//        spu
        //spu更新
        spuBo.setLastUpdateTime(new Date());//更新数据
        spuBo.setCreateTime(null);//--不更新的数据
        spuBo.setValid(null);
        spuBo.setSaleable(null);
        this.spuMapper.updateByPrimaryKeySelective(spuBo);

        //spuDetail
        this.spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());

        //   RABBITMQ发送同步消息给goods和search
        sendMsg("update",spuBo.getId());
    }

    /**
     * 查询单个spu通过id
     *
     * @param id id
     * @return {@link Spu}
     */
    public Spu querySpuById(Long id) {
        return this.spuMapper.selectByPrimaryKey(id);
    }
    /**
     * 查询单个sku通过id
     *
     * @param skuId id
     * @return {@link Spu}
     */
    public Sku querySkuById(Long skuId) {
        return this.skuMapper.selectByPrimaryKey(skuId);
    }

    public Integer querySkuStockBySkuId(Long skuId) {
        Stock stock = this.stockMapper.selectByPrimaryKey(skuId);
        return stock.getStock();//返回库存
    }
}
